const wx2my = require('../../wx2my');

// pages/integral/integral.js
const app = getApp();
let page = 1;
let totalpage;
Page({
  data: {
    onOff: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},
  onReady: function () {},
  onShow: function () {
    page = 1;
    this.get_list();
  },

  get_list() {
    let that = this;
    app.wxRequest('exchange_list', {
      'token': wx2my.getStorageSync('token'),
      'page': page
    }, function (res) {
      console.log(res);
      let list = res.data.data.list.list;
      let allIntegral = res.data.data.integral;

      if (page == 1) {
        totalpage = res.data.data.list.totalpage;
      }

      that.setData({
        allIntegral: allIntegral,
        list: page == 1 ? list : that.data.list.concat(list),
        lock: totalpage <= page ? true : false
      });
    });
  },

  change(e) {
    let that = this;
    if (that.data.onOff) return false;
    that.setData({
      onOff: 1
    });
    let integral = e.currentTarget.dataset.integral;
    let id = e.currentTarget.dataset.id;

    if (parseFloat(that.data.allIntegral) > parseFloat(integral)) {
      app.wxRequest('exchange_coupon', {
        'token': wx2my.getStorageSync('token'),
        'coupon_id': id
      }, function (res) {
        console.log(res);

        if (res.data.code == 1) {
          app.toast(res.data.msg);
          setTimeout(() => {
            wx2my.navigateBack();
          }, 2000);
        } else {
          that.setData({
            onOff: 0
          });
          app.toast(res.data.msg);
        }
      });
    } else {}
  },

  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    page++;

    if (!this.data.lock) {
      this.get_list();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
});